package domain.web.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import domain.web.dao.RegionDao;
import domain.web.model.Region;

@Repository("regionDao")
public class RegionDaoImpl extends JdbcDaoSupport implements RegionDao {

	@Autowired
	private DataSource dataSource;

	@PostConstruct
	void init() {
		setDataSource(dataSource);
	}

	@Override
	public Region get(long id, String locale) {
		String sql = "SELECT Id, Name_" + locale
				+ " AS Name FROM Regions WHERE Id = ?";
		List<Map<String, Object>> results = getJdbcTemplate().queryForList(sql,
				id);
		return results.isEmpty() ? null : rowMapper(results.get(0));
	}

	@Override
	public List<Region> getList(String locale) {
		String sql = "SELECT Id, Name_" + locale + " AS Name FROM Regions";
		List<Map<String, Object>> results = getJdbcTemplate().queryForList(sql);
		List<Region> regions = new ArrayList<Region>();
		for (Map<String, Object> map : results) {
			regions.add(rowMapper(map));
		}
		return regions;
	}
	
	@Override
	public List<Region> getListByStore(long storeId, String locale) {
		String sql = "SELECT RegionId, Name_" + locale + " AS Name FROM RegionView WHERE StoreId = ?";
		List<Map<String, Object>> results = getJdbcTemplate().queryForList(sql, storeId);
		List<Region> regions = new ArrayList<Region>();
		for (Map<String, Object> map : results) {
			regions.add(rowMapper(map));
		}
		return regions;
	}

	private Region rowMapper(Map<String, Object> row) {
		Region region = new Region();
		region.setId((Long) row.get("RegionId"));
		region.setName((String) row.get("Name"));
		return region;
	}
}
